<template>
  <page-wrap back hide-tab title="附件简历" stayStill class="page">
    <template v-if="resumeList && resumeList.length">
      <view class="bigTitle"
        >使用AI简历诊断/简历模版需要先选择附件进行简历解析</view
      >
      <view class="resume-list">
        <view
          v-for="(item, index) in resumeList"
          class="resume-list-item"
          :key="item.id"
        >
          <view class="resume-list-item-main">
            <view
              class="resume-list-item-main-left"
              @click="handleDowload(item)"
            >
              <image :src="appendixImg"></image>
            </view>
            <view
              class="resume-list-item-main-middle"
              @click="handleDowload(item)"
            >
              <view class="title">
                <text>{{ item.attName }}</text>
                <text class="prior-show" v-if="item.isPriorShow == 1">
                  优先展示给HR
                </text>
              </view>
              <view class="date">
                <text>{{ item.updateTime }} 上传</text>
              </view>
            </view>
            <view
              class="resume-list-item-main-right"
              @click.stop="handleOption(item, index)"
            >
              <view class="btn-delete">
                <view class="btn-dot"></view>
                <view class="btn-dot"></view>
                <view class="btn-dot"></view>
              </view>
            </view>
          </view>
          <view class="resume-list-item-select" v-if="canSelect">
            <image
              :src="enclosureSelected"
              @click="handleSelectResumeItem(item)"
              v-if="selectedId == item.id"
            ></image>
            <image
              :src="enclosureUnSelect"
              @click="handleSelectResumeItem(item)"
              v-else
            ></image>
          </view>
          <view class="templateTag" v-if="item.uploadType == 1">
            简历模板
          </view>
        </view>
        <view class="bottomBtnContainer" v-if="canSelect">
          <u-button type="primary" @click="confirmSelect" class="btn-parse"
            >确定</u-button
          >
          <u-button @click="closeSelect" class="btn-upload">取消</u-button>
        </view>
        <view class="bottomBtnContainer" v-else>
          <u-button type="primary" @click="switchSelect" class="btn-parse"
            >简历解析</u-button
          >
          <u-button
            @click="handleUpload"
            class="btn-upload"
            :hair-line="false"
            :custom-style="{
              border: 'none',
              outline: 'none',
              'background-color': '#f5f5f5'
            }"
            >上传附件简历</u-button
          >
        </view>
      </view>
    </template>
    <template v-else>
      <view class="example">
        <view class="img-wrap">
          <image :src="exampleImg"></image>
        </view>
        <u-button type="primary" @click="handleUpload" class="btn-upload"
          >选择文件</u-button
        >
      </view>
    </template>
    <u-action-sheet
      :list="list"
      v-model="show"
      @click="clickAction"
      safe-area-inset-bottom
    ></u-action-sheet>
    <u-popup v-model="show_rename" mode="center">
      <view class="popupBox">
        <view class="title">修改简历名称</view>
        <u-field
          v-model="resumeRename"
          placeholder="请输入简历名称"
          label-width="0"
          :field-style="{
            background: '#efefef',
            paddingLeft: '10rpx'
          }"
          :focus="focusName"
          :clearable="false"
          maxlength="18"
        >
        </u-field>
        <view class="attention">*不可超过20个字符，不可带特殊字符</view>
        <view class="confirmBtn">
          <view class="cancel" @click="cancel">取消</view>
          <view class="save" @click="save">保存</view>
          <view></view>
        </view>
      </view>
    </u-popup>
  </page-wrap>
</template>

<script>
import {
  selectAll,
  update,
  remove,
  personAddAttachment,
  setAttachmentResumeFirstShow
} from '@/api/modules/resumeCreate';
import ShareMixin from '@/mixins/share';
import {
  getResumeData,
  syncDealResumeAnalysisAndSave,
  getResumeAnalysisRes
} from '@/api/modules/career';
import { uploadAction, uploadBaseUrl, getPersonDetail } from '@/api/index';
export default {
  mixins: [ShareMixin],
  data() {
    return {
      personId: uni.getStorageSync('person-id').slice(2) || undefined,
      selectedId: null,
      selectedItem: null,
      canSelect: false, //是否展开选择
      enclosureUnSelect: this.$imgBase + 'resume/enclosureUnSelect_new.svg',
      enclosureSelected: this.$imgBase + 'resume/enclosureSelected_new.svg',
      focusName: false,
      currentItem: {
        item: '',
        index: ''
      },
      resumeRename: '',
      show: false,
      show_rename: false,
      list: [
        {
          text: '重命名'
        },
        {
          text: '优先展示'
        },
        {
          text: '发送到邮箱'
        },
        {
          text: '删除',
          color: 'red'
        },
        {
          text: '简历解析'
        }
      ],
      personId: uni.getStorageSync('person-id').slice(2) || undefined,
      exampleImg: this.$imgBaseSelf + 'resume/example.png',
      appendixImg: this.$imgBaseSelf + 'resume/appendix_new.svg',
      resumeList: [],
      activeFile: {},
      showDeleteModel: false,
      content: '是否删除',
      timer: null,
      MAX_RETRY_TIMES: 5,
      retryCount: 0,
      resumeHasAnalysis: false
    };
  },
  created() {
    this.getPersonFuJianList();
  },
  methods: {
    //刷新简历,异步处理返回一个promise
    getResumeData() {
      return new Promise((resolve, reject) => {
        let param = {
          personId: this.personId,
          conditionArr: JSON.stringify({
            is_mp: 1
          })
        };
        getResumeData(param)
          .then((res) => {
            getApp().globalData.resumeInfo = res.data;
            resolve(true);
          })
          .catch((err) => {
            reject(false);
          });
      });
    },
    //刷新个人信息
    getPersonDetail() {
      {
        let param = {
          param: JSON.stringify({
            personId: this.personId
          }),
          where: '',
          slaveInfo: 1
        };
        getPersonDetail(param).then((res) => {
          let data = res.data || res;
          if (
            data.pic &&
            data.pic.indexOf('img.job1001.com/myUpload/pic.gif') >= 0
          ) {
            data.pic = this.$defalutAvatar;
          }
          getApp().globalData.userInfo = data;
        });
      }
    },
    handleSelectResumeItem(item) {
      this.selectedId = item.id;
      this.selectedItem = item;
    },
    switchSelect() {
      this.canSelect = true;
    },
    closeSelect() {
      this.selectedId = null;
      this.selectedItem = null;
      this.canSelect = false;
    },
    async syncDealResumeAnalysisAndSaveFn() {
      uni.showLoading({ title: '解析中...' });
      const params = {
        fileUrl: this.selectedItem.attUrl,
        personId: this.personId
      };
      const res = await syncDealResumeAnalysisAndSave(params);
      if (res.code == 200) {
        setTimeout(() => {
          this.startRequest();
        }, 1000);
      } else {
        uni.hideLoading();
        uni.showToast({
          title: res.status_desc,
          icon: 'none',
          duration: 1500
        });
      }
    },
    startRequest() {
      this.timer = setInterval(() => {
        if (this.retryCount < this.MAX_RETRY_TIMES) {
          this.getResumeAnalysisResFn();
        } else {
          clearInterval(this.timer);
        }
      }, 5000);
    },
    endRequest() {
      clearInterval(this.timer);
      uni.hideLoading();
      this.timer = null;
    },
    // 获取简历解析结果状态
    async getResumeAnalysisResFn() {
      try {
        const res = await getResumeAnalysisRes({
          personId: this.personId,
          fileUrl: this.selectedItem.attUrl,
          retryNum: this.retryCount + 1
        });
        if (res.code === 200) {
          const status = res.data;
          if (status == 0) {
            uni.showToast({
              title: '没有要解析的简历',
              icon: 'none',
              duration: 1500
            });
            this.endRequest();
          } else if (status == 1) {
            uni.showLoading({ title: '解析中...' });
          } else if (status == 2) {
            uni.showToast({
              title: '简历解析失败，请重试',
              icon: 'none',
              duration: 1500
            });
            this.endRequest();
          } else if (status == 3) {
            this.resumeHasAnalysis = true;
            this.endRequest();
            this.getResumeData();
            this.getPersonDetail();
            uni.showToast({
              title: '简历解析成功',
              icon: 'none',
              duration: 1500
            });
          } else {
            uni.showToast({
              title: '未知错误',
              icon: 'none',
              duration: 1500
            });
            this.endRequest();
          }
        } else {
          this.endRequest();
          uni.showToast({
            title: res.status_desc,
            icon: 'none',
            duration: 1500
          });
        }
      } catch (err) {
        this.endRequest();
        uni.showToast({
          title: err.message,
          icon: 'none',
          duration: 1500
        });
      }

      // 每次尝试后增加重试计数
      this.retryCount++;

      // 如果超过最大重试次数且仍然未解析完成
      if (!this.resumeHasAnalysis && this.retryCount >= this.MAX_RETRY_TIMES) {
        uni.showToast({
          title: '超过最大重试次数，简历仍在解析中，请稍后重新进来此页面',
          icon: 'none',
          duration: 1500
        });
        this.endRequest();
      }
    },
    confirmSelect() {
      if (!this.selectedItem) {
        uni.showToast({
          icon: 'none',
          title: '请先选择要解析的简历'
        });
        return;
      }
      uni.showModal({
        title: '',
        content: '简历解析后会覆盖当前在线简历信息，是否确定解析？',
        confirmColor: '#F75A3E',
        cancelColor: '##999999',
        success: (res) => {
          if (res.confirm) {
            this.syncDealResumeAnalysisAndSaveFn();
          }
        }
      });
    },
    handleOption(item, index) {
      this.show = true;
      this.currentItem.item = item;
      this.currentItem.index = index;
      this.selectedItem = item;
    },
    clickAction(index) {
      //重命名
      this.show = false;
      if (index == 0) {
        this.show_rename = true;
        this.focusName = true;
      } else if (index == 1) {
        // 点击优先展示按钮
        var currentAttachResume = this.currentItem.item;
        this.reqSetAttachmentResumeFirstShow(currentAttachResume.id);
      } else if (index == 2) {
        uni.navigateTo({
          url: `/pagesSub/resume/resumeTemplate/resumeDetail/dentToEmail?ifSave=0&id=${this.currentItem.item.id}`
        });
      } else if (index == 3) {
        this.handleDelete(this.currentItem);
      } else if (index == 4) {
        this.confirmSelect();
      }
    },
    cancel() {
      this.show_rename = false;
      this.resumeRename = '';
    },

    // 设置附件简历优先展示
    reqSetAttachmentResumeFirstShow(att_id) {
      uni.showLoading({
        title: '请等待',
        mask: false
      });

      setAttachmentResumeFirstShow({
        att_id: att_id,
        person_id: this.personId
      })
        .then((res) => {
          uni.hideLoading();
          var _data = res;
          if (_data.code == 200) {
            uni.showToast({
              icon: 'none',
              title: '设置成功'
            });
            this.getPersonFuJianList();
          } else {
            // 投递失败
            uni.showToast({
              title: _data.status_desc,
              icon: 'none'
            });
          }
        })
        .catch((err) => {
          uni.hideLoading();
        });
    },

    save() {
      uni.showLoading({
        title: '正在修改',
        mask: true
      });
      this.resumeRename = this.resumeRename.replace(
        /[`:_.~!@#$%^&* \+ =<>?"{}|, \/ ;' \\ [ \] ·~！@#￥%……&*——\+ ={}|《》？：“”【】、；‘’，。、]/g,
        ''
      );
      if (this.resumeRename.length > 20) {
        uni.showToast({ icon: 'none', title: '名称不得超过20字符' });
        return;
      }
      let params = {
        attName: this.resumeRename,
        id: this.currentItem.item.id
      };
      update(params).then((res) => {
        if (+res.code === 200) {
          uni.showToast({ icon: 'none', title: '修改成功' });
          this.getPersonFuJianList();
          this.show_rename = false;
          this.resumeRename = '';
        } else {
          uni.hideLoading();
          uni.showToast({ icon: 'none', title: res.status_desc });
        }
      });
    },
    getPersonFuJianList() {
      let param = {
        person_id: this.personId,
        attStatus: '1'
      };
      selectAll(param).then((res) => {
        if (+res.code === 200) {
          this.resumeList = res.data;
        }
      });
    },
    handleDelete({ item, index } = currentItem) {
      uni.showModal({
        title: '温馨提示',
        content: `确认删除简历附件《${item.attName}》？`,
        success: (modalRes) => {
          if (modalRes.confirm) {
            let param = {
              idList: [item.id]
            };
            remove(param).then((res) => {
              if (+res.code === 200) {
                uni.showToast({
                  icon: 'none',
                  title: '删除成功'
                });
                this.getPersonFuJianList();
              }
            });
          }
        }
      });
    },
    handleDowload(item) {
      uni.showLoading({
        title: '正在打开简历'
      });
      uni.downloadFile({
        url: item.attUrl,
        success: (res) => {
          if (+res.statusCode === 200) {
            uni.saveFile({
              tempFilePath: res.tempFilePath,
              success: function (saveRes) {
                setTimeout(() => {
                  uni.hideLoading();
                  uni.openDocument({
                    filePath: saveRes.savedFilePath
                  });
                }, 1500);
              }
            });
          }
        }
      });
    },
    handleUpload() {
      // #ifdef H5
      // let uploadApi = uni.chooseFile;
      // #endif
      // #ifdef MP-WEIXIN
      if (this.resumeList.length >= 3) {
        return uni.showToast({
          icon: 'none',
          title: '最多可保存3个附件简历'
        });
      }
      let uploadApi = wx.chooseMessageFile;
      // #endif
      const TYPE = ['.doc', '.docx', '.pdf'];
      uploadApi({
        count: 1, //默认100
        extension: TYPE,
        success: (res) => {
          let tempFilePaths = res.tempFiles;
          let fileExt = '.' + tempFilePaths[0].name.replace(/.+\./, '');
          if (TYPE.indexOf(fileExt) < 0) {
            return uni.showToast({
              icon: 'none',
              title: '请选择pdf类型文件'
            });
          }
          if (tempFilePaths[0].size / (1024 * 1024) > 10) {
            return uni.showToast({
              icon: 'none',
              title: '文件大小不能超过10M'
            });
          }
          uni.showLoading({
            title: '正在上传'
          });
          uni.uploadFile({
            url: uploadAction,
            filePath: tempFilePaths[0].path,
            name: 'file',
            success: (uploadRes) => {
              let param = {
                personId: this.personId,
                attUrl: uploadBaseUrl + uploadRes.data,
                attName: tempFilePaths[0].name
              };
              personAddAttachment(param).then((fujianRes) => {
                uni.hideLoading();
                if (fujianRes.code === 200) {
                  uni.showToast({
                    icon: 'none',
                    title: '上传成功'
                  });
                  this.getPersonFuJianList();
                }
              });
            }
          });
        }
      });
    }
  }
};
</script>

<style lang="scss">
.bigTitle {
  margin: 32rpx 32rpx 0;
  color: #c34e4e;
}
.example {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  padding: 32rpx 32rpx 0;
  box-sizing: border-box;
  .img-wrap {
    flex-grow: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    image {
      width: 694rpx;
      height: 1043rpx;
    }
  }
  .btn-upload {
    bottom: 80rpx;
    position: fixed;
    flex-shrink: 0;
    width: calc(100% - 64rpx);
  }
}

.resume-list {
  margin: 32rpx;
  position: relative;
  .bottomBtnContainer {
    position: fixed;
    bottom: 0;
    left: 0;
    background-color: white;
    height: 292rpx;
    width: 100vw;
    .btn-upload {
      bottom: 80rpx;
      position: fixed;
      flex-shrink: 0;
      width: calc(100% - 64rpx);
      border: 0;
      left: 50%;
      transform: translateX(-50%);
    }
    .btn-parse {
      bottom: 180rpx;
      position: fixed;
      flex-shrink: 0;
      width: calc(100% - 64rpx);
      border: 0;
      left: 50%;
      transform: translateX(-50%);
    }
  }

  &-item {
    position: relative;
    display: flex;
    align-items: center;
    // border-radius: $uni-border-radius-big;
    .templateTag {
      position: absolute;
      top: 0;
      left: 0;
      padding: 5rpx 10rpx;
      background: #ffebdc;
      border-radius: 8rpx 0rpx 8rpx 0rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 22rpx;
      color: #eb8232;
      line-height: 22rpx;
      text-align: left;
      font-style: normal;
    }
    &-main {
      display: flex;
      align-items: center;
      background-color: $uni-bg-color;
      margin-bottom: 16rpx;
      padding: 24rpx;
      flex: 1;
      &-left {
        margin-right: 24rpx;
        image {
          // margin: 0 14rpx;
          width: 68rpx;
          height: 68rpx;
          margin-top: 4rpx;
        }
      }
      &-middle {
        flex: 1;
        width: 0;
        .title {
          min-width: 260rpx;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 32rpx;
          color: #222222;
          line-height: 40rpx;
          text-align: left;
          font-style: normal;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
          margin-bottom: 12rpx;
          display: flex;
          flex-direction: row;
          align-items: center;

          .prior-show {
            color: #fb675c;
            padding-left: 10rpx;
            padding-right: 10rpx;
            padding-top: 5rpx;
            font-size: 28rpx;
            margin-left: 10rpx;
            padding-bottom: 5rpx;
            border: 1rpx solid #fb675c;
          }
        }
        .date {
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 24rpx;
          color: #bfa0a0;
          line-height: 32rpx;
          text-align: left;
          font-style: normal;
        }
      }
      &-right {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: 20rpx;
        .btn-delete {
          display: flex;
          align-items: center;
          justify-content: space-evenly;
          width: 40rpx;
          height: 40rpx;
          // background-image: url($img-base + "delete.png");
          background-size: 100% 100%;
          .btn-dot {
            width: 7rpx;
            height: 7rpx;
            border-radius: 50%;
            background: #a4a4a4;
          }
        }
      }
    }
    &-select {
      image {
        width: 47rpx;
        height: 47rpx;
        margin-left: 20rpx;
      }
    }
  }
}
.popupBox {
  width: 60vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .title {
    font-size: 16px;
    font-weight: 600;
    padding-top: 40rpx;
  }
  .attention {
    font-size: 10px;
    color: #f75a3e;
    width: 100%;
    padding-left: 28rpx;
  }
  .confirmBtn {
    margin-top: 20rpx;
    height: 60rpx;
    width: 100%;
    font-size: 13px;
    display: flex;
    .cancel {
      color: #f75a3e;
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      border-bottom-left-radius: 20rpx;
    }
    .save {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #f75a3e;
      color: #fff;
      border-bottom-right-radius: 20rpx;
    }
  }
}
::v-deep .u-mode-center-box {
  border-radius: 20rpx;
}
::v-deep .u-field {
  padding-bottom: 10rpx !important;
}
</style>
